//
//  NetWorkTools.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/4/23.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit
import AFNetworking

class NetWorkTools: AFHTTPSessionManager {
    
    static let sharInstance: NetWorkTools = {
        
        let basicsURL = URL(string: "https://api.weibo.com/")!

        let instance = NetWorkTools(baseURL: basicsURL, sessionConfiguration: .default)
        
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String>
        
        return instance
    }()
    
    func post(_ URLString: String, parameters: Any?, success: ((Any?) -> Void)?, failure: ((Error) -> Void)?) {
        self.post(URLString, parameters: parameters, progress: { (_) in
            
        }, success: { (task, objc) in
            success!(objc)
        }) { (task, error) in
            failure!(error)
        }
    }
    
    func get(_ URLString: String, parameters: Any?, success: ((Any?) -> Void)?, failure: ((Error) -> Void)?) {
        self.get(URLString, parameters: parameters, progress: { (_) in
            
        }, success: { (task, objc) in
            success!(objc)
        }) { (task, error) in
            failure!(error)
        }
    }

    
    // MARK: - 外部控制方法
    func loadStatuses(since_id: String, max_id: String, finished:  @escaping (_ array: [[String: Any]]?, _ error: NSError?)->())
    {
        assert(UserAcount.loadUserAccount() != nil, "必须授权之后才能获取微博数据")
        
        // 1.准备路径
        let path = "2/statuses/home_timeline.json"
        // 2.准备参数
        let temp = (max_id != "0") ? "\(Int(max_id)! - 1)" : max_id
        let parameters = ["access_token": UserAcount.loadUserAccount()!.access_token!, "since_id": since_id, "max_id": temp]
        // 3.发送GET请求
        get(path, parameters: parameters, success: { (result) in
            // 返回数据给调用者
            guard let arr = (result as! [String: Any])["statuses"] as? [[String: Any]] else
            {
                finished(nil, NSError(domain: "com.520it.lnj", code: 1000, userInfo: ["message": "没有获取到数据"]))
                return
            }
            
            finished(arr, nil)
        }) { (error) in
            finished(nil, error as NSError)
        }
    }
}
